﻿using System;
using System.Collections.Generic;
using System.Linq;
using BITS.PreCompiler.CSharp.Syntax.Extensions;
using BITS.PreCompiler.CSharp.Visitors.Extensions;
using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;

namespace BITS.PreCompiler.CSharp
{
    public partial class Unit
    {
        # region • Methods •

        /// <summary>
        /// Gets the syntax tree.
        /// </summary>
        /// <returns></returns>
        public SyntaxTree GetSyntaxTree()
        {
            return SyntaxTree.ParseText(
                this.ToString());
        }

        /// <summary>
        /// Gets the compilation.
        /// </summary>
        /// <returns></returns>
        public Compilation GetCompilation(IEnumerable<String> references)
        {
            return this.GetCompilation(references.Select(
                MetadataReference.CreateAssemblyReference));
        }

        /// <summary>
        /// Gets the compilation.
        /// </summary>
        /// <returns></returns>
        public Compilation GetCompilation(IEnumerable<MetadataReference> references = null)
        {
            if (references == null)
            {
                references = new List<MetadataReference>
                {
                    MetadataReference.CreateAssemblyReference(typeof(Object).Assembly.Location),
                };
            }

            var usingList = new List<String>();

            new Visitors.SyntaxVisitor()
                .UsingHandler(x => usingList.Add(x.Name))
            .Visit(this);

            return Compilation.Create(this.OutputName)
                .WithOptions(new CompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                .AddSyntaxTrees(this.GetSyntaxTrees())
                .AddReferences(references)
                .WithUsings(usingList);
        }

        # endregion Methods
    }
}
